// File: src/ui/qt/KingdonWindow.cpp
#include "KingdomWindow.h"
#include <QGraphicsDropShadowEffect>
KingdomWindow::KingdomWindow(XPSystem& xpSystem, 
                           std::vector<Territory>& territories,
                           std::string& username,
                           QWidget *parent): QMainWindow(parent),
      m_xpSystem(xpSystem),
      m_territories(territories),
      m_username(username),
      m_taskManager(this),
      m_daemon(m_taskManager), //设置reminder
      m_taskTable(nullptr), 
      m_addTaskBtn(nullptr),
      m_deleteTaskBtn(nullptr),
      m_filterByDateBtn(nullptr),
      m_filterByMonthBtn(nullptr),
      m_clearFilterBtn(nullptr),
      m_dateFilterEdit(nullptr),
      m_monthFilterEdit(nullptr)
      {
        // 加载图片、音频等资源
        Q_INIT_RESOURCE(resources);
        // 专用提醒播放器
        reminderPlayer = new QMediaPlayer(this);
        QAudioOutput* reminderOutput = new QAudioOutput(this);
        reminderPlayer->setAudioOutput(reminderOutput);
        reminderOutput->setVolume(0.8f);
        // 初始化音频播放器
        audioPlayer = new QMediaPlayer(this);
        QAudioOutput* audioOutput = new QAudioOutput(this); // 创建音频输出
        audioPlayer->setAudioOutput(audioOutput); // 关联到媒体播放器
        audioOutput->setVolume(0.8f); // 设置音量

        // 初始化UI组件
        setWindowTitle("时间王国");
        resize(800, 600);  // 扩大窗口以适应任务管理功能
        setupUI();
        m_xpSystem.loadFromFile(m_username, m_territories); // 加载XP值

        QString exeDir = QCoreApplication::applicationDirPath();
        // 清理旧文件
        QString recordFile = QDir(exeDir)
                        .absoluteFilePath("voice_record.pcm");
        if (QFile::exists(recordFile)) {
            QFile::remove(recordFile);
        }
        
        m_voiceRecognition = new VoiceRecognition(exeDir, this); // 加载录音工具
        // 根据token调用BaiduASR
        m_baiduASR = new BaiduASR("hsAT214DjooZrtr4CUThYBRq", "lJ5leDs73hJXJsh8dh3aqXZysCWtHBn0", this);
        setConnect();// 连接信号槽
        
        // 领土图标加载
        m_territoryIcons[TerritoryType::CASTLE] = QIcon("../resources/icons/castle.png");
        m_territoryIcons[TerritoryType::FOREST] = QIcon("../resources/icons/forest.png");
        m_territoryIcons[TerritoryType::MOUNTAIN] = QIcon("../resources/icons/mountain.png");
        m_territoryIcons[TerritoryType::RIVER] = QIcon("../resources/icons/river.png");
        
        m_taskManager.loadTasks(m_username); // 初始加载
        m_daemon.start();// 提醒线程开始
        refreshTasks();
        updateDisplay();
    }

void KingdomWindow::setConnect(){
    // 连接信号槽
        // 按钮信号槽
        connect(m_addTaskBtn, &QPushButton::clicked, 
            this, &KingdomWindow::onAddTaskClicked);
        connect(m_deleteTaskBtn, &QPushButton::clicked, 
            this, &KingdomWindow::onDeleteTaskClicked);
        connect(m_filterByDateBtn, &QPushButton::clicked, 
            this, &KingdomWindow::onFilterByDateClicked);
        connect(m_filterByMonthBtn, &QPushButton::clicked, 
            this, &KingdomWindow::onFilterByMonthClicked);
        connect(m_clearFilterBtn, &QPushButton::clicked, 
            this, &KingdomWindow::onClearFilterClicked);
        connect(m_reminderDismissBtn, &QPushButton::clicked, 
            this, &KingdomWindow::dismissReminder);
        connect(m_voiceControlBtn, &QPushButton::clicked,
            this, &KingdomWindow::onVoiceControlClicked); // 连接语音控制按钮
    
        // 请求函数信号槽    
        connect(this, &KingdomWindow::requestAddTask,
           this, &KingdomWindow::addTask, Qt::QueuedConnection);
        connect(this, &KingdomWindow::requestDeleteTask, 
            this, &KingdomWindow::deleteTask, Qt::QueuedConnection);
        connect(this, &KingdomWindow::requestFilterByDate, 
            this, &KingdomWindow::filterByDate, Qt::QueuedConnection);
        connect(this, &KingdomWindow::requestFilterByMonth, 
            this, &KingdomWindow::filterByMonth, Qt::QueuedConnection);
        connect(this, &KingdomWindow::requestClearFilter, 
            this, &KingdomWindow::clearFilter, Qt::QueuedConnection);

        connect(&m_taskManager, &TaskManager::reminderTriggered, 
            this, &KingdomWindow::showReminder);

        connect(m_voiceControlBtn, &QPushButton::clicked, 
            this, &KingdomWindow::onVoiceControlClicked, Qt::QueuedConnection);
        connect(m_voiceRecognition, &VoiceRecognition::recordingStopped, 
            this, &KingdomWindow::onRecordingFinished, Qt::QueuedConnection);
        connect(m_baiduASR, &BaiduASR::recognitionFinished, 
            this, &KingdomWindow::handleVoiceCommand, Qt::QueuedConnection);
        connect(m_baiduASR, &BaiduASR::recognitionError, 
            this, &KingdomWindow::handleVoiceError, Qt::QueuedConnection);
}

void KingdomWindow::closeEvent(QCloseEvent* event) {
    m_xpSystem.saveToFile(m_username, m_territories); // 保存XP值
    QMainWindow::closeEvent(event); // 调用父类关闭逻辑
}

bool KingdomWindow::showLoginDialog(QString& outUsername, QString& outPassword, bool& outIsRegister) {
    QDialog dialog;
    dialog.setWindowTitle("登录时间王国");
    dialog.setFixedSize(300, 250); // 固定对话框大小

    // 用户名和密码输入框
    QLineEdit* usernameEdit = new QLineEdit(&dialog);
    QLineEdit* passwordEdit = new QLineEdit(&dialog);
    passwordEdit->setEchoMode(QLineEdit::Password);

    // 注册提示文字（红色小字）
    QLabel* hintLabel = new QLabel("提示：输入不存在的用户名将自动注册", &dialog);
    hintLabel->setStyleSheet("font-size: 10px; color: #ff0000;");

    QDialogButtonBox* buttons = new QDialogButtonBox(&dialog);
    QPushButton* loginBtn = buttons->addButton("登录/注册", QDialogButtonBox::AcceptRole);
    QPushButton* cancelBtn = buttons->addButton("取消", QDialogButtonBox::RejectRole);

    QFormLayout* layout = new QFormLayout(&dialog);
    layout->addRow("用户名:", usernameEdit);
    layout->addRow("密码:", passwordEdit);
    layout->addRow(hintLabel);
    layout->addWidget(buttons);

    // 处理按钮点击
    bool isAccepted = false;
    QObject::connect(loginBtn, &QPushButton::clicked, [&]() {
        outUsername = usernameEdit->text().trimmed();
        outPassword = passwordEdit->text();
        if (outUsername.isEmpty() || outPassword.isEmpty()) {
            QMessageBox::warning(&dialog, "错误", "用户名和密码不能为空");
            return;
        }
        outIsRegister = true; // 标记可能需要注册
        dialog.accept();
        isAccepted = true;
    });

    QObject::connect(cancelBtn, &QPushButton::clicked, &dialog, &QDialog::reject);

    return (dialog.exec() == QDialog::Accepted) && isAccepted;
}

void KingdomWindow::initTaskTable()
{
    // 配置表格属性
    m_taskTable->setColumnCount(6);
    m_taskTable->setHorizontalHeaderLabels(
        {"ID", "任务名称", "开始时间", "优先级", "分类", "提醒时间"});
    
    // 设置列宽策略
    m_taskTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    m_taskTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    m_taskTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    m_taskTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
    m_taskTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
    m_taskTable->horizontalHeader()->setSectionResizeMode(5, QHeaderView::ResizeToContents);

    // 启用排序
    m_taskTable->setSortingEnabled(true);
    
    // 禁止编辑
    m_taskTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 单行选择模式
    m_taskTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_taskTable->setSelectionMode(QAbstractItemView::SingleSelection);
}

void KingdomWindow::setupReminderPanel()
{
    // 提醒界面布局
    m_reminderPanel = new QWidget(this);
    m_reminderPanel->setStyleSheet(
        "background-color: #fff9e6;"  // 浅黄色背景
        "border: 1px solid #ffe8a1;"  // 金色边框
        "border-radius: 10px;"        // 圆角
        "padding: 12px;"
        "margin-bottom: 15px;"
    );
    m_reminderPanel->setVisible(false);  // 默认不可见
    
    QVBoxLayout* reminderLayout = new QVBoxLayout(m_reminderPanel);
    reminderLayout->setContentsMargins(5, 5, 5, 5);  // 设置内边距
    
    m_reminderLabel = new QLabel("暂无提醒", m_reminderPanel);  // 默认文本
    m_reminderLabel->setStyleSheet(
        "font-weight: bold; color: #856404;"
        "font-size: 14px;"
    );
    m_reminderLabel->setWordWrap(true);
    m_reminderLabel->setAlignment(Qt::AlignCenter);
    
    m_reminderDismissBtn = new QPushButton("我知道了", m_reminderPanel);
    m_reminderDismissBtn->setStyleSheet(
        "QPushButton {"
        "  background-color: #ffeeba;"
        "  border: 1px solid #ffdf7e;"
        "  border-radius: 3px;"
        "  padding: 5px 10px;"
        "  min-width: 80px;"
        "}"
        "QPushButton:hover {"
        "  background-color: #ffdf7e;"
        "}"
    );
    
    reminderLayout->addWidget(m_reminderLabel);
    reminderLayout->addWidget(m_reminderDismissBtn, 0, Qt::AlignCenter);  // 居中按钮
}

void KingdomWindow::setupUI()
{
    QWidget* centralWidget = new QWidget(this);
    //总布局
    QVBoxLayout* mainLayout = new QVBoxLayout(centralWidget); 
    mainLayout->setContentsMargins(10, 10, 10, 10);  // 添加边距
    mainLayout->setSpacing(10);  // 设置间距

    //提醒窗格
    setupReminderPanel();// 将提醒窗格添加到主布局最上方
    
    // 修改标题样式 - 使用花体并添加阴影效果
    m_titleLabel = new QLabel("你的时间王国", this);
    m_titleLabel->setStyleSheet(
        "font-size: 32px;"
        "font-weight: bold;"
        "color: #5a4a9c;"  // 柔和的紫色
        "font-family: 'Brush Script MT', cursive;"  // 花体字体
        "text-shadow: 2px 2px 4px rgba(0,0,0,0.2);"  // 文字阴影
    );
    m_titleLabel->setAlignment(Qt::AlignCenter);
    
    // 添加装饰性副标题
    QLabel* subtitle = new QLabel("管理你的时间，扩展你的王国", this);
    subtitle->setStyleSheet(
        "font-size: 16px;"
        "color: #7d6ba0;"
        "font-style: italic;"
        "margin-bottom: 15px;"
    );
    subtitle->setAlignment(Qt::AlignCenter);
    
    // 在总布局中添加副标题
    mainLayout->insertWidget(1, subtitle);

    // 设置整体窗口样式
    centralWidget->setStyleSheet(
        "QWidget {"
        "   background-color: #f8f5ff;"  // 浅紫色背景
        "   font-family: 'Segoe UI', Arial, sans-serif;"
        "}"
        "QProgressBar {"
        "   border: 2px solid #c0b3d9;"
        "   border-radius: 6px;"
        "   text-align: center;"
        "   height: 18px;"
        "}"
        "QProgressBar::chunk {"
        "   background-color: #9b8ccd;"  // 柔和的紫色
        "   border-radius: 4px;"
        "}"
        "QTableWidget {"
        "   background-color: white;"
        "   border-radius: 8px;"
        "   border: 1px solid #d9d1e9;"
        "   gridline-color: #eae4f5;"
        "   alternate-background-color: #f5f1ff;"  // 交替行颜色
        "}"
        "QHeaderView::section {"
        "   background-color: #d9d1e9;"
        "   padding: 4px;"
        "   border: 1px solid #c0b3d9;"
        "   font-weight: bold;"
        "}"
        "QPushButton {"
        "   background-color: #9b8ccd;"  // 紫色按钮
        "   color: white;"
        "   border-radius: 6px;"
        "   padding: 6px 12px;"
        "   font-weight: bold;"
        "   min-width: 80px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #8877c0;"  // 悬停时变深
        "}"
        "QPushButton:pressed {"
        "   background-color: #7565b3;"  // 按下时更深
        "}"
        "QLineEdit, QDateEdit {"
        "   background-color: white;"
        "   border: 1px solid #c0b3d9;"
        "   border-radius: 4px;"
        "   padding: 4px;"
        "}"
        "QScrollArea {"
        "   border: none;"
        "   background: transparent;"
        "}"
    );

    // 添加背景纹理
    QWidget* background = new QWidget(centralWidget);
    background->setStyleSheet(
        "background-image: url(:/textures/parchment.jpg);"  // 假设有羊皮纸纹理资源
        "background-repeat: no-repeat;"
        "background-position: center;"
        "border-radius: 12px;"
    );
    background->setGeometry(centralWidget->rect());
    centralWidget->stackUnder(background);  // 将背景放在最底层

    // 等级和XP显示
    QWidget* xpWidget = new QWidget(this);
    QHBoxLayout* xpLayout = new QHBoxLayout(xpWidget);
    
    m_levelLabel = new QLabel(this);
    m_levelLabel->setStyleSheet("font-size: 18px;");
    
    m_xpProgress = new QProgressBar(this);
    m_xpProgress->setRange(0, m_xpSystem.getXPToNextLevel());
    m_xpProgress->setTextVisible(false);
    m_xpProgress->setStyleSheet(
        "QProgressBar { border: 2px solid grey; border-radius: 5px; }"
        "QProgressBar::chunk { background-color: #3498db; }"
    );
    
    m_xpLabel = new QLabel(this);
    m_xpLabel->setStyleSheet("font-size: 14px;");
    
    xpLayout->addWidget(m_levelLabel);
    xpLayout->addWidget(m_xpProgress, 1);
    xpLayout->addWidget(m_xpLabel);
    
    // 领土显示
    m_territoriesWidget = new QWidget(this);
    m_territoriesWidget->setStyleSheet(
        "background-color: lightblue;"  // 设置背景透明
        "border: none;"            // 去除边框
    );
    QVBoxLayout* territoriesLayout = new QVBoxLayout(m_territoriesWidget);
    territoriesLayout->setAlignment(Qt::AlignTop);

    QLabel* territoriesTitle = new QLabel("领土", this);
    territoriesTitle->setStyleSheet("font-size: 20px; font-weight: bold; color: #2c3e50;");
    territoriesLayout->addWidget(territoriesTitle);

    // 将领土设置为可滚动的
    QScrollArea* territoriesScrollArea = new QScrollArea(this);
    territoriesScrollArea->setWidgetResizable(true); // 允许内容区域扩展
    territoriesScrollArea->setWidget(m_territoriesWidget); // 将领土区域放入滚动区域
    territoriesScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 禁用水平滚动
    territoriesScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);    // 启用垂直滚动

    // 任务表格界面
    m_taskTable = new QTableWidget(this);
    m_taskTable->setMinimumHeight(200); // 设置最小高度

    initTaskTable();// 初始化表格
    
    // 生成功能按钮
    m_addTaskBtn = new QPushButton("添加任务", this);
    m_deleteTaskBtn = new QPushButton("删除任务", this);
    m_filterByDateBtn = new QPushButton("按日筛选", this);
    m_filterByMonthBtn = new QPushButton("按月筛选", this);
    m_clearFilterBtn = new QPushButton("清除筛选", this);
    // 生成过滤器和删除任务输入框
    m_dateFilterEdit = new QDateEdit(QDate::currentDate(), this);
    m_dateFilterEdit->setDisplayFormat("yyyy-MM-dd");
    
    m_monthFilterEdit = new QDateEdit(QDate::currentDate(), this);
    m_monthFilterEdit->setDisplayFormat("yyyy-MM");

    m_taskIdInput = new QLineEdit(this);
    m_taskIdInput->setPlaceholderText("输入任务ID");

    // 任务管理子布局
    QVBoxLayout* taskLayout = new QVBoxLayout();
    taskLayout->addWidget(new QLabel("任务管理"));
    taskLayout->addWidget(m_taskTable);

    // 筛选部件
    QHBoxLayout* filterLayout = new QHBoxLayout();
    filterLayout->addWidget(new QLabel("筛选:"));
    filterLayout->addWidget(m_dateFilterEdit);
    filterLayout->addWidget(m_filterByDateBtn);
    filterLayout->addWidget(m_monthFilterEdit);
    filterLayout->addWidget(m_filterByMonthBtn);
    filterLayout->addWidget(m_clearFilterBtn);
    filterLayout->addStretch();
    
   // 按钮布局
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(m_addTaskBtn);
    buttonLayout->addWidget(m_taskIdInput);
    buttonLayout->addWidget(m_deleteTaskBtn);
    buttonLayout->addStretch(); // 添加弹性空间将语音按钮推到右侧
    
    // 创建语音控制按钮和状态标签的容器
    QWidget* voiceControlWidget = new QWidget(this);
    QHBoxLayout* voiceLayout = new QHBoxLayout(voiceControlWidget);
    voiceLayout->setContentsMargins(0, 0, 0, 0);
    voiceLayout->setSpacing(5);
    //语音状态标签
    m_voiceStatusLabel = new QLabel("点击麦克风开始语音控制", this);
    m_voiceStatusLabel->setStyleSheet("color: #7f8c8d; font-size: 12px;");
    //语音控制按钮
    m_voiceControlBtn = new QPushButton(this);
    m_voiceControlBtn->setIcon(QIcon("../resources/icons/microphone.png"));
    m_voiceControlBtn->setIconSize(QSize(24, 24));
    m_voiceControlBtn->setToolTip("语音控制");
    m_voiceControlBtn->setStyleSheet(
        "QPushButton { border: none; background: transparent; }"
        "QPushButton:hover { background: #f0f0f0; border-radius: 12px; }"
    );
    // 在语音控制部件中添加帮助按钮
    QPushButton* voiceHelpBtn = new QPushButton(this);
    voiceHelpBtn->setIcon(QIcon("../resources/icons/help.png"));
    voiceHelpBtn->setIconSize(QSize(20, 20));
    voiceHelpBtn->setToolTip("语音帮助");
    voiceHelpBtn->setStyleSheet(
        "QPushButton { border: none; background: transparent; }"
        "QPushButton:hover { background: #f0f0f0; border-radius: 10px; }"
    );
    connect(voiceHelpBtn, &QPushButton::clicked, 
            this, &KingdomWindow::showVoiceCommandHelp);
    
    voiceLayout->addWidget(m_voiceStatusLabel);
    voiceLayout->addWidget(m_voiceControlBtn);
    voiceLayout->addWidget(voiceHelpBtn);  // 添加帮助按钮

    voiceLayout->addWidget(m_voiceStatusLabel);
    voiceLayout->addWidget(m_voiceControlBtn);
    // 将语音控制容器添加到按钮布局的最右侧
    buttonLayout->addWidget(voiceControlWidget);
    
    taskLayout->addLayout(filterLayout);
    taskLayout->addLayout(buttonLayout);
    
    //组装在总体布局
    mainLayout->insertWidget(0, m_reminderPanel);
    mainLayout->addWidget(m_titleLabel);
    mainLayout->addWidget(xpWidget);
    mainLayout->addWidget(territoriesScrollArea, 1);
    mainLayout->addLayout(taskLayout, 0);  
    
    centralWidget->setLayout(mainLayout);
    setCentralWidget(centralWidget);
}

void KingdomWindow::updateDisplay()
{
    // 更新等级和XP
    QString levelText = QString("等级: %1 ★").arg(m_xpSystem.getCurrentLevel());
    m_levelLabel->setText(levelText);
    
    m_xpProgress->setMaximum(m_xpSystem.getXPToNextLevel()+m_xpSystem.getCurrentXP());
    m_xpProgress->setValue(m_xpSystem.getCurrentXP());

    QString xpText = QString("%1/%2 XP").arg(m_xpSystem.getCurrentXP())
                                       .arg(m_xpSystem.getXPToNextLevel());
    m_xpLabel->setText(xpText);
    
    // 更新领土
    QLayout* layout = m_territoriesWidget->layout();
    
    // 清除现有领土显示（保留标题）
    while (layout->count() > 1) {
        QLayoutItem* item = layout->takeAt(1);
        if (item->widget()) {
            delete item->widget();
        }
        delete item;
    }
    
    if (m_territories.empty()) {
        QLabel* emptyLabel = new QLabel("还没有领土，添加任务来扩展你的王国吧！", this);
        emptyLabel->setStyleSheet(
            "color: #7d6ba0;"  // 柔和的紫色
            "font-style: italic;"
            "font-size: 14px;"
            "padding: 10px;"
            "text-align: center;"
        );
        layout->addWidget(emptyLabel);
    } else {
        for (const auto& territory : m_territories) {
            // 创建领土卡片容器
            QWidget* territoryCard = new QWidget(this);
            territoryCard->setStyleSheet(
                "background-color: rgba(255, 255, 255, 0.85);"  // 半透明白色背景
                "border-radius: 12px;"                          // 圆角
                "border: 1px solid #d9d1e9;"                    // 浅紫色边框
            );
            territoryCard->setFixedHeight(60); // 增加高度给卡片更多空间
            
            // 添加阴影效果
            QGraphicsDropShadowEffect* shadow = new QGraphicsDropShadowEffect;
            shadow->setBlurRadius(10);
            shadow->setOffset(3, 3);
            shadow->setColor(QColor(90, 74, 156, 50)); // 柔和的紫色阴影
            territoryCard->setGraphicsEffect(shadow);
            
            // 卡片内部布局
            QHBoxLayout* cardLayout = new QHBoxLayout(territoryCard);
            cardLayout->setContentsMargins(15, 10, 15, 10); // 增加内边距
            cardLayout->setSpacing(15);
            
            // 领土名称
            QLabel* nameLabel = new QLabel(territory.getName().c_str(), territoryCard);
            nameLabel->setStyleSheet(
                "font-weight: bold;"
                "font-size: 16px;"
                "color: #5a4a9c;"  // 主色调紫色
                "min-width: 120px;"
            );
            
            // 图标容器
            QWidget* iconContainer = new QWidget(territoryCard);
            iconContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            QHBoxLayout* iconLayout = new QHBoxLayout(iconContainer);
            iconLayout->setSpacing(5); // 增加图标间距
            iconLayout->setContentsMargins(0, 0, 0, 0);
            
            // 添加领土图标
            for (int i = 0; i < territory.getSize(); ++i) {
                QLabel* iconLabel = new QLabel(iconContainer);
                iconLabel->setPixmap(
                    m_territoryIcons[territory.getType()].pixmap(32, 32) // 增大图标尺寸
                );
                iconLabel->setFixedSize(32, 32);
                
                // 添加图标悬停效果
                iconLabel->setStyleSheet(
                    "QLabel {"
                    "   border-radius: 6px;"
                    "   padding: 2px;"
                    "}"
                    "QLabel:hover {"
                    "   background-color: #f0ebfa;"  // 悬停时浅紫色背景
                    "}"
                );
                iconLayout->addWidget(iconLabel);
            }
            
            // 领土大小
            QLabel* sizeLabel = new QLabel(QString("(%1)").arg(territory.getSize()), territoryCard);
            sizeLabel->setStyleSheet(
                "color: #9b8ccd;"  // 柔和的紫色
                "font-size: 14px;"
                "font-weight: bold;"
                "min-width: 40px;"
            );
            
            // 进度条显示领土大小
            QProgressBar* sizeBar = new QProgressBar(territoryCard);
            sizeBar->setRange(0, territory.getSize());
            sizeBar->setValue(territory.getSize());
            sizeBar->setTextVisible(false);
            sizeBar->setStyleSheet(
                "QProgressBar {"
                "   height: 10px;"
                "   border: 1px solid #c0b3d9;"
                "   border-radius: 5px;"
                "   background-color: #eae4f5;"
                "}"
                "QProgressBar::chunk {"
                "   background-color: #9b8ccd;"  // 紫色进度条
                "   border-radius: 4px;"
                "}"
            );
            
            // 添加到卡片布局
            cardLayout->addWidget(nameLabel);
            cardLayout->addWidget(iconContainer, 1); // 图标区域可伸缩
            cardLayout->addWidget(sizeLabel);
            cardLayout->addWidget(sizeBar, 2); // 进度条占据更多空间
            
            // 添加到主布局
            layout->addWidget(territoryCard);
        }
    }
    
    // 添加装饰性分隔线
    QFrame* separator = new QFrame(this);
    separator->setFrameShape(QFrame::HLine);
    separator->setFrameShadow(QFrame::Sunken);
    separator->setStyleSheet("color: #d9d1e9; margin: 10px 0;");
    layout->addWidget(separator);
}

void KingdomWindow::onAddTaskClicked() {
    // 弹出对话框获取任务信息
    QDialog dialog(this);
    dialog.setWindowTitle("添加新任务");
    
    // 表单组件
    QLineEdit* nameEdit = new QLineEdit(&dialog);
    QDateTimeEdit* dateEdit = new QDateTimeEdit(QDateTime::currentDateTime(), &dialog);
    dateEdit->setDisplayFormat("yyyy-MM-dd HH:mm");
    QComboBox* priorityCombo = new QComboBox(&dialog);
    priorityCombo->addItems({"低", "中", "高"});
    QComboBox* categoryCombo = new QComboBox(&dialog);
    categoryCombo->addItems({"学习", "工作", "娱乐", "生活"});
    QDateTimeEdit* remindEdit = new QDateTimeEdit(&dialog);
    remindEdit->setDisplayFormat("yyyy-MM-dd HH:mm");
    
    
    // 按钮组
    QDialogButtonBox* buttons = new QDialogButtonBox(
        QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
        &dialog
    );

    // 布局
    QFormLayout* layout = new QFormLayout(&dialog);
    layout->addRow("任务名称:", nameEdit);
    layout->addRow("开始时间:", dateEdit);
    layout->addRow("优先级:", priorityCombo);
    layout->addRow("分类:", categoryCombo);
    layout->addRow("提醒时间:", remindEdit);
    layout->addWidget(buttons);

    // 连接信号
    connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    // 执行对话框
    if (dialog.exec() == QDialog::Accepted) {
        // 获取输入值
        QString name = nameEdit->text().trimmed();
        QDateTime dateTime = dateEdit->dateTime();
        QString priority = priorityCombo->currentText();
        QString category = categoryCombo->currentText();
        QDateTime remindTime = remindEdit->dateTime();

        // 验证输入
        if (name.isEmpty()) {
            QMessageBox::warning(this, "错误", "任务名称不能为空");
            return;
        }

        if (dateTime < QDateTime::currentDateTime()) {
            QMessageBox::warning(this, "错误", "开始时间不能早于当前时间");
            return;
        }

        // 映射到CLI兼容值
        static const QHash<QString, QString> priorityMap = {
            {"低", "low"}, {"中", "medium"}, {"高", "high"}
        };
        static const QHash<QString, QString> categoryMap = {
            {"学习", "study"}, {"工作", "work"}, 
            {"娱乐", "entertainment"}, {"生活", "life"}
        };

        // 发射信号
        emit requestAddTask(
            name,
            dateTime,
            priorityMap.value(priority, "medium"),
            categoryMap.value(category, "life"),
            remindTime
        );
    }
}

void KingdomWindow::addTask(const QString& name, const QDateTime& dateTime,
                          const QString& priority, const QString& category
                        ,const QDateTime& remindTime) {
    try {
        QDateTime tempStart = dateTime;
        tempStart.setTime(QTime(dateTime.time().hour(), dateTime.time().minute(), 0));// 从分钟开始截断
        std::time_t startTime = tempStart.toSecsSinceEpoch();// 转换为时间戳
        if (m_taskManager.taskExists(name.toStdString(), startTime)) {
            QMessageBox::warning(this, "错误", "任务已存在（名称和开始时间相同）");
            return;
        }
        // 构建参数
        Task task(
            name.toStdString(),
            startTime, 
            convertPriority(priority),
            convertCategory(category),
            remindTime.toSecsSinceEpoch()
        );
        task.setId(m_taskManager.getNextId());
        // std::cout << "Assigning ID:" << task.getId() << std::endl;
        // 添加并保存任务
        m_taskManager.loadTasks(m_username, true); // 确保加载最新数据
        if (m_taskManager.addTask(task)) {
            m_taskManager.saveTasks(m_username); // 显式保存
            // 游戏化: 添加XP
            int xp = 0;
            switch (convertPriority(priority)) {
                case Priority::LOW: xp = 10; break;
                case Priority::MEDIUM: xp = 20; break;
                case Priority::HIGH: xp = 30; break;
            }
            m_xpSystem.addXP(xp);

            // 游戏化: 扩展领土
            TerritoryType territoryType = 
                getTerritoryTypeForCategory(convertCategory(category));
            auto it = std::find_if(m_territories.begin(), m_territories.end(),
                [territoryType](const Territory& t) { return t.getType() == territoryType; });

            if (it != m_territories.end()) {
                it->expand();
            }
            else {
                m_territories.emplace_back(territoryType);
            }
            std::cout << "获得 " << xp << " XP! 当前XP: " << m_xpSystem.getCurrentXP() << std::endl;
            refreshTasks();
            updateDisplay();
        }
    } catch (const std::exception& e) {
        QMessageBox::critical(this, "错误", QString("添加任务失败: %1").arg(e.what()));
    }
}

void KingdomWindow::refreshTasks() {
    m_taskTable->setRowCount(0);
    
    try {
        m_taskManager.loadTasks(m_username, true); 
        auto tasks = m_taskManager.getAllTasks();

        // 填充表格
        m_taskTable->setRowCount(tasks.size());
        for (int row = 0; row < tasks.size(); ++row) {
            const auto& task = tasks[row];
            
            // ID列
            m_taskTable->setItem(row, 0, 
                new QTableWidgetItem(QString::number(task.getId())));
            
            // 名称列
            m_taskTable->setItem(row, 1,
                new QTableWidgetItem(QString::fromStdString(task.getName())));
            
            // 时间列（格式化为yyyy-MM-dd HH:mm）
            //QDateTime time = QDateTime::fromTime_t(task.getStartTime());
            QDateTime time = QDateTime::fromSecsSinceEpoch(task.getStartTime());
            m_taskTable->setItem(row, 2,
                new QTableWidgetItem(time.toString("yyyy-MM-dd HH:mm")));
            
            // 优先级列
            m_taskTable->setItem(row, 3,
                new QTableWidgetItem(QString::fromStdString(task.getPriorityString())));
            
            // 分类列
            m_taskTable->setItem(row, 4,
                new QTableWidgetItem(QString::fromStdString(task.getCategoryString())));
            
            // 提醒时间列（格式化为yyyy-MM-dd HH:mm）
            QDateTime remindTime = QDateTime::fromSecsSinceEpoch(task.getRemindTime());
            m_taskTable->setItem(row, 5,
                new QTableWidgetItem(remindTime.toString("yyyy-MM-dd HH:mm")));
        }
    } catch (const std::exception& e) {
        QMessageBox::warning(this, "错误", 
            QString("加载任务失败: %1").arg(e.what()));
    }
}

void KingdomWindow::onDeleteTaskClicked()
{
    bool ok;
    int taskId = m_taskIdInput->text().toInt(&ok);
    
    if (!ok || taskId <= 0) {
        QMessageBox::warning(this, "错误", "请输入有效的任务ID");
        return;
    }
    
    emit requestDeleteTask(taskId);
}

void KingdomWindow::deleteTask(int taskId)
{
    try {
        std::string taskName = m_taskManager.getTask(taskId).getName();
        Category category = m_taskManager.getTask(taskId).getCategory();

        // 弹出确认对话框
        QMessageBox confirmDialog(this);
        confirmDialog.setWindowTitle("删除任务");
        confirmDialog.setText(QString("确定要删除任务: %1?").arg(QString::fromStdString(taskName)));
        // 添加自定义按钮
        QPushButton *completedButton = confirmDialog.addButton("任务已完成", QMessageBox::AcceptRole);
        QPushButton *notCompletedButton = confirmDialog.addButton("任务未完成", QMessageBox::RejectRole);
        confirmDialog.addButton(QMessageBox::Cancel);
        
        confirmDialog.setIcon(QMessageBox::Question);
        confirmDialog.exec();

        if (confirmDialog.clickedButton() == completedButton) {
            // 用户标记任务为已完成 - 正常删除，不惩罚
            if (m_taskManager.removeTask(taskId)) {
                m_taskManager.saveTasks(m_username);
                QMessageBox::information(this, "成功", "任务已标记为完成并删除");
                refreshTasks();
                updateDisplay();
            }
        } 

        else if (confirmDialog.clickedButton() == notCompletedButton) {
            // 用户标记任务为未完成 - 执行惩罚逻辑
            if (m_taskManager.removeTask(taskId)) {
                m_taskManager.saveTasks(m_username);
                
                // 游戏化惩罚: 缩减领土和扣除XP
                m_xpSystem.addXP(-15); // 扣除15XP
                std::cout << "扣除 15 XP! 当前XP: " << m_xpSystem.getCurrentXP() << std::endl;
                
                TerritoryType territoryType = getTerritoryTypeForCategory(category);
                auto it = std::find_if(m_territories.begin(), m_territories.end(),
                    [territoryType](const Territory& t) { return t.getType() == territoryType; });

                if (it != m_territories.end()) {
                    it->shrink(); // 领土缩减
                }
                
                QMessageBox::information(this, "提示", "任务已删除，但因未完成扣除XP，缩减领土");
                refreshTasks();
                updateDisplay();
            }
        }
        // 如果点击Cancel则不执行任何操作
        /*
        if (m_taskManager.removeTask(taskId)) {
            m_taskManager.saveTasks(m_username);
            QMessageBox::information(this, "成功", "任务删除成功");

            // 游戏化: 缩减领土
            m_xpSystem.addXP(-15);
            std::cout << "扣除 15 XP! 当前XP: " << m_xpSystem.getCurrentXP() << std::endl;
            TerritoryType territoryType = getTerritoryTypeForCategory(category);
            auto it = std::find_if(m_territories.begin(), m_territories.end(),
                [territoryType](const Territory& t) { return t.getType() == territoryType; });

            if (it != m_territories.end()) {
                it->shrink();
            }
            
            refreshTasks();
            updateDisplay();
        } else {
            QMessageBox::warning(this, "错误", "未找到指定ID的任务");
        }*/
    } catch (const std::exception& e) {
        QMessageBox::critical(this, "错误", QString("删除任务失败: %1").arg(e.what()));
    }
}

// 添加筛选功能
void KingdomWindow::onFilterByDateClicked()
{
    emit requestFilterByDate(m_dateFilterEdit->date());
}

void KingdomWindow::onFilterByMonthClicked()
{
    emit requestFilterByMonth(m_monthFilterEdit->date());
}

void KingdomWindow::onClearFilterClicked()
{
    emit requestClearFilter();
}

void KingdomWindow::filterByDate(QDate date)
{
    try {
        std::time_t timestamp = QDateTime(date, QTime(0, 0)).toSecsSinceEpoch();
        auto filteredTasks = m_taskManager.getTasksForDay(timestamp);
        
        m_taskTable->setRowCount(0);
        m_taskTable->setRowCount(filteredTasks.size());
        
        for (int row = 0; row < filteredTasks.size(); ++row) {
            const auto& task = filteredTasks[row];
            
            m_taskTable->setItem(row, 0, new QTableWidgetItem(QString::number(task.getId())));
            m_taskTable->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(task.getName())));
            
            QDateTime time = QDateTime::fromSecsSinceEpoch(task.getStartTime());
            m_taskTable->setItem(row, 2, new QTableWidgetItem(time.toString("yyyy-MM-dd HH:mm")));
            
            m_taskTable->setItem(row, 3, new QTableWidgetItem(QString::fromStdString(task.getPriorityString())));
            m_taskTable->setItem(row, 4, new QTableWidgetItem(QString::fromStdString(task.getCategoryString())));
            
            QDateTime remindTime = QDateTime::fromSecsSinceEpoch(task.getRemindTime());
            m_taskTable->setItem(row, 5, new QTableWidgetItem(remindTime.toString("yyyy-MM-dd HH:mm")));
        }
    } catch (const std::exception& e) {
        QMessageBox::warning(this, "错误", QString("筛选任务失败: %1").arg(e.what()));
    }
}

void KingdomWindow::filterByMonth(QDate date)
{
    try {
        std::time_t timestamp = QDateTime(date, QTime(0, 0)).toSecsSinceEpoch();
        auto filteredTasks = m_taskManager.getTasksForMonth(timestamp);
        
        m_taskTable->setRowCount(0);
        m_taskTable->setRowCount(filteredTasks.size());
        
        for (int row = 0; row < filteredTasks.size(); ++row) {
            const auto& task = filteredTasks[row];
            
            m_taskTable->setItem(row, 0, new QTableWidgetItem(QString::number(task.getId())));
            m_taskTable->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(task.getName())));
            
            QDateTime time = QDateTime::fromSecsSinceEpoch(task.getStartTime());
            m_taskTable->setItem(row, 2, new QTableWidgetItem(time.toString("yyyy-MM-dd HH:mm")));
            
            m_taskTable->setItem(row, 3, new QTableWidgetItem(QString::fromStdString(task.getPriorityString())));
            m_taskTable->setItem(row, 4, new QTableWidgetItem(QString::fromStdString(task.getCategoryString())));
            
            QDateTime remindTime = QDateTime::fromSecsSinceEpoch(task.getRemindTime());
            m_taskTable->setItem(row, 5, new QTableWidgetItem(remindTime.toString("yyyy-MM-dd HH:mm")));
        }
    } catch (const std::exception& e) {
        QMessageBox::warning(this, "错误", QString("筛选任务失败: %1").arg(e.what()));
    }
}

void KingdomWindow::clearFilter()
{
    refreshTasks(); // 重新加载所有任务
}
// 添加专用播放函数
void KingdomWindow::playReminderSound(const QString& resourcePath) {
    // 停止当前可能正在播放的提醒
    if (reminderPlayer->playbackState() == QMediaPlayer::PlayingState) {
        reminderPlayer->stop();
    }
    
    // 设置资源路径
    reminderPlayer->setSource(QUrl(resourcePath));
    
    // 直接播放（不检查文件存在性，因为资源已在qrc中）
    reminderPlayer->play();
}
//提醒功能函数
void KingdomWindow::showReminder(const QString& message, int priority) {
    // 直接更新UI（已在主线程）
    m_reminderLabel->setText(message);
    m_reminderPanel->setVisible(true);
    
    // 根据优先级选择声音文件
    QString soundFile;
    switch (static_cast<Priority>(priority)) {
        case Priority::HIGH: soundFile = "../resources/sounds/alarm_high.wav"; break;
        case Priority::MEDIUM: soundFile = "../resources/sounds/alarm_high.wav"; break;
        case Priority::LOW: 
        default: soundFile = "../resources/sounds/alarm_high.wav"; break;
    }
    
    // 直接播放声音
    playReminderSound(soundFile);
}


void KingdomWindow::dismissReminder() {
    // 停止提醒声音
    if (reminderPlayer->playbackState() == QMediaPlayer::PlayingState) {
        reminderPlayer->stop();
    }
    
    // 更新UI
    m_reminderLabel->setText("暂无提醒");
    m_reminderPanel->setVisible(false);
}

// 音频处理模块
void KingdomWindow::playSound(const QString& relativePath) {
    // 获取应用程序目录
    QString appDir = QCoreApplication::applicationDirPath();
    
    // 构造绝对路径
    QString soundPath = QDir(appDir).filePath(relativePath);
    
    // 检查文件是否存在
    if (!QFile::exists(soundPath)) {
        qDebug() << "Sound file not found:" << soundPath;
        // 尝试使用资源路径
        QString resourcePath = ":/" + relativePath;
        if (QFile::exists(resourcePath)) {
            soundPath = resourcePath;
            qDebug() << "Using resource path:" << resourcePath;
        } else {
            qDebug() << "Resource file not found:" << resourcePath;
            // 回退到系统提示音
            QApplication::beep();
            return;
        }
    }
    
    qDebug() << "Playing sound:" << soundPath;
    
    // 停止当前播放
    if (audioPlayer->audioOutput()) {
        audioPlayer->stop();
    }
    
    // 设置媒体源
    audioPlayer->setSource(QUrl::fromLocalFile(soundPath));
    
    // 处理加载状态
    connect(audioPlayer, &QMediaPlayer::mediaStatusChanged, this, 
        [this](QMediaPlayer::MediaStatus status) {
            if (status == QMediaPlayer::LoadedMedia) {
                qDebug() << "Media loaded, starting playback";
                audioPlayer->play();
            } else if (status == QMediaPlayer::InvalidMedia) {
                qDebug() << "Invalid media, error:" << audioPlayer->errorString();
                // 回退到系统提示音
                QApplication::beep();
            }
        }, Qt::SingleShotConnection); // 一次性连接
    
    // 处理播放错误
    connect(audioPlayer, &QMediaPlayer::errorOccurred, this, 
        [](QMediaPlayer::Error error, const QString &errorString) {
            qDebug() << "Playback error:" << errorString;
            // 回退到系统提示音
            QApplication::beep();
        }, Qt::SingleShotConnection);
    
    // 如果媒体已经加载完成，直接播放
    if (audioPlayer->mediaStatus() == QMediaPlayer::LoadedMedia) {
        audioPlayer->play();
    }
}
// 保证线程安全的消息转发函数
/*void KingdomWindow::postVoiceCommand(const QString& command) {
    QMetaObject::invokeMethod(this, [this, command]() {
        handleVoiceCommand(command);
    }, Qt::QueuedConnection);
}*/

/*void KingdomWindow::postVoiceError(const QString& error) {
    QMetaObject::invokeMethod(this, [this, error]() {
        handleVoiceError(error);
    }, Qt::QueuedConnection);
}*/
// 在 KingdomWindow 类中添加辅助函数
int KingdomWindow::chineseToArabic(const QString& chineseNum) {
    static const QMap<QString, int> numMap = {
        {"一", 1}, {"二", 2}, {"三", 3}, {"四", 4}, {"五", 5},
        {"六", 6}, {"七", 7}, {"八", 8}, {"九", 9}, {"十", 10},
        {"十一", 11}, {"十二", 12}, {"十三", 13}, {"十四", 14}, {"十五", 15},
        {"十六", 16}, {"十七", 17}, {"十八", 18}, {"十九", 19}, {"二十", 20},
        {"二十一", 21}, {"二十二", 22}, {"二十三", 23}, {"二十四", 24}, {"二十五", 25},
        {"二十六", 26}, {"二十七", 27}, {"二十八", 28}, {"二十九", 29}, {"三十", 30},
        {"三十一", 31}, {"三十二", 32}, {"三十三", 33}, {"三十四", 34}, {"三十五", 35},
        {"三十六", 36}, {"三十七", 37}, {"三十八", 38}, {"三十九", 39}, {"四十", 40},
        {"四十一", 41}, {"四十二", 42}, {"四十三", 43}, {"四十四", 44}, {"四十五", 45},
        {"四十六", 46}, {"四十七", 47}, {"四十八", 48}, {"四十九", 49}, {"五十", 50}
    };
    return numMap.value(chineseNum, -1);
}
// 音频处理函数
void KingdomWindow::handleVoiceCommand(const QString &command) {
    // 清理识别结果：移除标点符号和多余空格
    QString cleanCmd = command;
    cleanCmd.replace(QRegularExpression("[.,。，!！?？]"), ""); // 移除标点
    cleanCmd = cleanCmd.simplified(); // 移除多余空格
    cleanCmd = cleanCmd.toLower();    // 转换为小写
    
    qDebug() << "清理后的命令:" << cleanCmd;
    m_voiceStatusLabel->setText("识别结果: " + cleanCmd);
    
    // 命令匹配逻辑 - 修复逻辑表达式
    if (cleanCmd.contains("添加任务") || cleanCmd.contains("新任务") || 
        cleanCmd.contains("增加任务") || cleanCmd == "1" || cleanCmd == "一") {
        qDebug() << "执行添加任务命令";
        onAddTaskClicked();
    } 
    else if (cleanCmd.contains("删除任务") || cleanCmd == "2" || cleanCmd == "二") {
        // 支持两种格式：删除任务1 / 删除任务一
        QRegularExpression re1("删除任务\\s*(\\d+)");    // 阿拉伯数字
        QRegularExpression re2("删除任务\\s*([一二三四五六七八九十]+)"); // 中文数字
        
        QRegularExpressionMatch match = re1.match(cleanCmd);
        int taskId = -1;
        
        if (match.hasMatch()) {
            taskId = match.captured(1).toInt();
        } else {
            match = re2.match(cleanCmd);
            if (match.hasMatch()) {
                QString chineseNum = match.captured(1);
                taskId = chineseToArabic(chineseNum);
            }
        }
        
        if (taskId > 0) {
            m_taskIdInput->setText(QString::number(taskId));
            onDeleteTaskClicked();
        } else {
            QMessageBox::information(this, "提示", 
                "请说'删除任务'后加上任务ID，例如'删除任务123'或'删除任务一'");
        }
    }
    else if (cleanCmd.contains("今天") || cleanCmd.contains("当日") || 
             cleanCmd == "3" || cleanCmd == "三") {
        qDebug() << "筛选今日任务";
        onFilterByDateClicked();
    }
    else if (cleanCmd.contains("本月") || cleanCmd.contains("这个月") || 
             cleanCmd == "4" || cleanCmd == "四") {
        qDebug() << "筛选本月任务";
        onFilterByMonthClicked();
    }
    else if (cleanCmd.contains("清除") || cleanCmd.contains("全部") || 
             cleanCmd == "5" || cleanCmd == "五") {
        qDebug() << "清除筛选";
        onClearFilterClicked();
    }
    else if (cleanCmd.contains("帮助") || cleanCmd.contains("说明") || 
             cleanCmd == "6" || cleanCmd == "六") {
        qDebug() << "显示帮助";
        showVoiceCommandHelp();
    }
    else {
        // // 播放错误提示音
        // audioPlayer->setSource(QUrl(":/sounds/error.wav"));  // 使用资源路径
        // audioPlayer->play();
        // 播放前添加调试，打印当前工作目录和文件是否存在
        playSound("../resources/sounds/error.wav");

        QString message = "未识别命令: " + cleanCmd + "\n\n";
        message += "可用命令:\n";
        message += "1. 添加任务\n";
        message += "2. 删除任务[ID]\n";
        message += "3. 今天/本月 (筛选任务)\n";
        message += "4. 清除筛选\n";
        message += "5. 帮助";
        
        QMessageBox::information(this, "语音命令", message);
    }
    
    // // 添加语音反馈
    // audioPlayer->setSource(QUrl(":/sounds/confirm.wav"));  // 使用资源路径
    // audioPlayer->play();
    // 播放前添加调试，打印当前工作目录和文件是否存在
    // 暂时注释确认音乐playSound("../resources/sounds/confirm.wav");
    // 3秒后恢复状态提示
    QTimer::singleShot(3000, this, [this]() {
        m_voiceStatusLabel->setText("点击麦克风开始语音控制");
    });
}

void KingdomWindow::handleVoiceError(const QString& error) {
    qDebug() << "处理语音错误(主线程):" << QThread::currentThreadId() << error;
    m_voiceStatusLabel->setText("识别错误: " + error);
    QTimer::singleShot(3000, this, [this]() {
        m_voiceStatusLabel->setText("点击麦克风开始语音控制");
    });
}


// 语音控制按钮点击事件
void KingdomWindow::onVoiceControlClicked() {
    m_voiceControlBtn->setEnabled(false);
    // 按键消抖功能
    QTimer::singleShot(200, this, [this]() { // 200ms后恢复按钮
        m_voiceControlBtn->setEnabled(true);
    });
    if (m_voiceRecognition->isRecording()) {
        QTimer::singleShot(100, this, [this]() {
            m_voiceRecognition->stopRecording();
        });
        m_voiceStatusLabel->setText("录音已停止");
    } else {
        QTimer::singleShot(100, this, [this]() {
            m_voiceRecognition->startRecording();
        });
        m_voiceStatusLabel->setText("正在录音...");
    }
}

// 录音完成后的处理
void KingdomWindow::onRecordingFinished() {
    QString filePath = m_voiceRecognition->getRecordedFilePath();
    m_voiceStatusLabel->setText("正在识别...");
    m_baiduASR->recognizeFromFile(filePath);  // 调用BaiduASR识别
    m_voiceStatusLabel->setText("识别完成");
}
void KingdomWindow::showVoiceCommandHelp()
{
    // 创建更友好的帮助对话框
    QDialog helpDialog(this);
    helpDialog.setWindowTitle("语音命令帮助");
    helpDialog.resize(500, 400);
    
    QVBoxLayout *layout = new QVBoxLayout(&helpDialog);
    
    // 标题
    QLabel *title = new QLabel("时间王国语音控制指南");
    title->setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50;");
    layout->addWidget(title, 0, Qt::AlignCenter);
    
    // 分隔线
    QFrame *line = new QFrame();
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    layout->addWidget(line);
    
    // 命令列表
    QTextEdit *helpText = new QTextEdit();
    helpText->setReadOnly(true);
    helpText->setHtml(
        "<h3>基本语音命令：</h3>"
        "<ul>"
        "<li><b>添加任务</b> - 打开添加任务对话框</li>"
        "<li><b>删除任务 + ID</b> - 删除指定ID的任务（例如：删除任务123）</li>"
        "<li><b>今天</b> - 显示今天的任务</li>"
        "<li><b>本月</b> - 显示本月的任务</li>"
        "<li><b>清除筛选</b> - 显示所有任务</li>"
        "<li><b>帮助</b> - 显示此帮助信息</li>"
        "</ul>"
        
        "<h3>数字快捷命令：</h3>"
        "<ul>"
        "<li><b>一</b> - 添加任务</li>"
        "<li><b>二</b> - 删除任务</li>"
        "<li><b>三</b> - 显示今天任务</li>"
        "<li><b>四</b> - 显示本月任务</li>"
        "<li><b>五</b> - 清除筛选</li>"
        "<li><b>六</b> - 显示帮助</li>"
        "</ul>"
        
        "<h3>使用技巧：</h3>"
        "<ul>"
        "<li>在安静环境下使用语音功能</li>"
        "<li>说话时距离麦克风20-30厘米</li>"
        "<li>每句命令后稍作停顿</li>"
        "<li>复杂的命令请分多次说出</li>"
        "</ul>"
    );
    
    layout->addWidget(helpText);
    
    // 确定按钮
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok);
    connect(buttonBox, &QDialogButtonBox::accepted, &helpDialog, &QDialog::accept);
    layout->addWidget(buttonBox);
    
    helpDialog.exec();
}
// void KingdomWindow::showVoiceCommandHelp()
// {
//     QMessageBox::information(this, "语音命令帮助",
//         "可用语音命令:\n\n"
//         "1. '添加任务' - 打开添加任务对话框\n"
//         "2. '删除任务[ID]' - 删除指定ID的任务\n"
//         "3. '筛选今天' - 显示今天的任务\n"
//         "4. '清除筛选' - 显示所有任务\n"
//         "5. '帮助' - 显示此帮助信息");
// }